<?php

namespace app\common\service;

use app\common\model\Member;
use app\common\model\MemberThird;
use Overtrue\Socialite\Contracts\UserInterface;
use think\App;
use think\facade\Db;

class MemberService extends AbstractService
{
    const Wechat = 'wechat';

    public function __construct(App $app)
    {
        parent::__construct($app);

    }

    public function addMemberThird(UserInterface $thirdUser, $member_id = 0, $platform = self::Wechat)
    {
//        $model = new MemberThird();
        $mThird = MemberThird::where('openid', $thirdUser->getId())->strict(false)->findOrEmpty();
        $mThird->data([
            'member_id' => $member_id,
            'platform' => $platform,
            'unionid' => $thirdUser->getId(),
            'openid' => $thirdUser->getId(),
            'nickname' => $thirdUser->getNickname(),
            'avatar' => $thirdUser->getAvatar(),
            //  'sex' =>  $thirdUser->getId(),
            //  'birthday' date DEFAULT NULL COMMENT '生日',
            //  'country' varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '国家',
            'province' => $thirdUser->getProvider(),
            //  'city' varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '市',
            'access_token' => $thirdUser->getAccessToken(),
            'refresh_token' => $thirdUser->getRefreshToken(),
            'expires_in' => $thirdUser->getExpiresIn(),
            //  'create_time' int unsigned DEFAULT NULL COMMENT '创建时间',
            //  'update_time' int unsigned DEFAULT NULL COMMENT '更新时间',
            'login_time' => time(),
            //  'expire_time' int unsigned DEFAULT NULL COMMENT '过期时间',
            //  'delete_time' int DEFAULT '0' COMMENT '删除时间',
        ])->save();
        return $mThird->toArray();
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 登陆
     */
    public function login($data)
    {
        $member = Member::whereOr([
            [['email', '=', $data['username']]],
            [['username', '=', $data['username']]],
            [['mobile', '=', $data['username']]]
        ])->find();

        if (!$member) throw new \Exception('用户不存在');
        if ($member && $member->status == 0) throw new \Exception('账户已停用，请联系管理员');
//        if (strlen($data['password']) < 6) throw new \Exception('password length cannot be less than 6 characters');
//        if (!captcha_check($data['vercode'])) throw new \Exception('verification_code_error');
        if (!password_verify($data['password'], $member->password)) throw new \Exception('密码错误，请重新登录');
        $data['password'] = password_hash($data['password'], PASSWORD_BCRYPT);
        $member->login_num = $member->login_num + 1;
        $member->last_ip = $_SERVER['REMOTE_ADDR'];
        $member->last_login = time();
        $member->token = token();
        $member->login_time = time();
        if (!$member->save()) throw new \Exception('登录失败');
        $_COOKIE['mid'] = $member->id;
        session('mid', $member->id);
//        session('member', $member->toArray());
    }

    /**
     * @return bool
     * 注册
     */
    public function reg($data)
    {
        Db::startTrans();
        try {
            $member = Member::where('username', $data['username'])->find();
            if ($member) throw new \Exception('手机号码已存在');
            if ($member && $member->status == 0) throw new \Exception('手机已停用，请联系客服');
//            if (!captcha_check($data['vercode'])) throw new \Exception('验证码错误');
            $num = rand(0, 13);
            $data['avatar'] = '/static/frontend/images/avatar/' . $num . '.jpg';
            $data['password'] = password_hash($data['password'], PASSWORD_BCRYPT);
            $data['mobile'] = $data['username'];
            if (session('?openid')) {
                $mUser = MemberThird::where(['openid' => session('openid')])->find();
                if ($mUser) {
                    $data['avatar'] = $mUser['avatar'];
                    $data['nickname'] = $mUser['nickname'];
                }
            }
            session('regData', $data);
            $member_id = Member::create($data)->getLastInsID();
            MemberThird::where('openid', session('openid'))->update(['member_id' => $member_id]);
            $member = Member::where('username', $data['username'])->find();
            session('member', $member);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollBack();
            throw new \Exception($e->getMessage());
        }

    }

    //发送邮件
//    public function sendEmail($member)
//    {
//        $data = [$member->username, $member->email, $member->password];
//        $token = json_decode(cookie('activeToken'));
//        $validity = 2 * 3600;//有限期
//        if (!$token || ($token && $token['time'] < time() - $validity)) {
//            $token = StringHelper::getToken($data);//验证码
//            $tokenData = ['time' => $validity, 'token' => $token, 'member_id' => $member->id];
//        }
//        $link = __u('member/emailactive', ['token' => $token]);
////        $content = $this->_geteamilContent($validity / 3600, $link);
//        $param = ['to' => $member->email, 'subject' => 'FunAdmin 社区激活邮件', 'content' => $content];
//        $mail = json_decode(hook('sendEmail', $param), true);
//        if ($mail['code'] > 0) {
//            cookie('activeToken', json_encode($tokenData));
//        } else {
//            throw new Exception($mail['msg']);
//        }
//        return true;
//    }
}
